//
//  CQCookiesManager.m
//  YZStock
//
//  Created by fenchol on 15/7/7.
//  Copyright (c) 2015年 fenchol. All rights reserved.
//

#import "YZCookiesManager.h"
#import "YZRequestURLs.h"

#define sYZMHttpCookieXTCEDefault   @"YZMHttpCookieXTCEDefault"

@implementation YZCookiesManager

+ (void)saveXTCECookiesForResponse: (NSHTTPURLResponse *)response
{
    NSArray *cookies = [NSHTTPCookie cookiesWithResponseHeaderFields:[response allHeaderFields] forURL:[NSURL URLWithString:URL_BASE_STRING]];
    
    for (NSHTTPCookie *cookie in cookies)
    {
        if ([cookie.name isEqualToString:@"X-TCE"]) {
            
            NSMutableArray *localCookies = [NSMutableArray arrayWithArray:[[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:[NSURL URLWithString:URL_BASE_STRING]]];
            NSMutableDictionary *dic = [NSMutableDictionary dictionary];
            [dic setValue:[cookie value] forKey:NSHTTPCookieValue];
            [dic setValue:[cookie name] forKey:NSHTTPCookieName];
            
            /*设置新的Cookie的值*/
            if ([localCookies count]) {
                
                NSHTTPCookie *cookie = [localCookies objectAtIndex:0];
                [dic setObject:[cookie domain] forKey:NSHTTPCookieDomain];
                [dic setObject:[cookie path] forKey:NSHTTPCookiePath];
                
            }else{
                
                [dic setObject:@".yztz.com" forKey:NSHTTPCookieDomain];
                [dic setObject:@"/" forKey:NSHTTPCookiePath];
                
            }
            
            NSHTTPCookie *instance = [[NSHTTPCookie alloc] initWithProperties:dic];
            if (instance) {
                [localCookies addObject:instance];
            }
            
            [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookies:localCookies forURL:[NSURL URLWithString:URL_BASE_STRING] mainDocumentURL:nil];
            [[NSUserDefaults standardUserDefaults] setObject: [cookie value] forKey: sYZMHttpCookieXTCEDefault];
            
            
            break;
        }
    }
}

+ (void)clearUserSession
{
    NSArray * cookArray = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:[NSURL URLWithString:URL_BASE_STRING]];
    
    for (NSHTTPCookie*cookie in cookArray) {
        
        if ([cookie.name isEqualToString:@"JSESSIONID"]){
            
            [[NSHTTPCookieStorage sharedHTTPCookieStorage] deleteCookie:cookie];
        }
    }
    
}

@end
